//
//  YCMainViewController.swift
//  WeiboDemo
//
//  Created by 尹成 on 2017/1/6.
//  Copyright © 2017年 yc. All rights reserved.
//

import UIKit

//1.extension 中不能有属性
//2.extension 中不能重写父类方法,重写是子类的职责,extension是对类的拓展

class YCMainViewController: UIViewController {
    
//    //用户登录标记
//    var userLogon = true
    
    //方可视图信息
    var visitorInfo : [String:String]?
    
    /// 表格视图 - 如果用户未登陆,则不创建
    var tableView:UITableView?
    
    /// 刷新控件
    var refreshControl:UIRefreshControl?
    
    /// 上拉刷新标记
    var isPullup = false
    
    lazy var ycnavigationbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    lazy var yctitleItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //登录后加载数据，否则不加载
        YCNetworkManager.shared.userLogon ? loadData() : ()
        
        NotificationCenter.default.addObserver(self, selector: #selector(logon), name: NSNotification.Name(rawValue: YCUserLoginSuccessNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override var title: String?{
        didSet{
            yctitleItem.title = title
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /// 加载数据,具体实现由子类负责,如果子类没有实现,调用默认处理方式
    func loadData() {
        
        refreshControl?.endRefreshing()
    }
    
}


// MARK: - 设置界面
extension YCMainViewController{
    fileprivate func setupUI(){
        
        //取消自动缩进
        automaticallyAdjustsScrollViewInsets = false
        
        setNavigationBar()
        YCNetworkManager.shared.userLogon ? setTableView() : setupVisitorView()
    }
    
    /// 设置表格视图
    func setTableView() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        //        view.addSubview(tableView!)
        view.insertSubview(tableView!, belowSubview: ycnavigationbar)
        
        ///设置数据/代理, 让子类直接实现数据源方法
        tableView?.dataSource = self
        tableView?.delegate = self
        
        tableView?.contentInset = UIEdgeInsets(top: ycnavigationbar.bounds.height,
                                               left: 0,
                                               bottom: tabBarController?.tabBar.bounds.height ?? 49,
                                               right: 0)
        
        //设置刷新控件
        refreshControl = UIRefreshControl()
        tableView?.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
    }
    
    private func setupVisitorView(){
        let visitorView = YCVisitorView(frame: view.bounds)
        view.insertSubview(visitorView, belowSubview: ycnavigationbar)
        visitorView.visitorInfo = visitorInfo
        
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
                
        if visitorInfo?["imageName"] == "" {
            yctitleItem.leftBarButtonItem = UIBarButtonItem(title: "登录", target: self, action: #selector(login))
            yctitleItem.rightBarButtonItem = UIBarButtonItem(title: "注册", target: self, action: #selector(register))
        }
    
    }
    
    /// 设置导航条
    private func setNavigationBar() {
        view.addSubview(ycnavigationbar)
        ycnavigationbar.items = [yctitleItem]
        ycnavigationbar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        //标题颜色
        ycnavigationbar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.orange]
        // 设置系统按钮的文字渲染颜色
        ycnavigationbar.tintColor = UIColor.orange
    }
    
}


// MARK: - 登录，注册 监听方法 【1.监听， 2.回调  ，3.代理 3.通知 4.kvc】
extension YCMainViewController{
    @objc fileprivate func login(){
        print("--login--")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YCUserShouldLoginNotification), object: nil)
    }
    @objc fileprivate func register(){
        print("--register--")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YCUserShouldRegisterNotification), object: nil)
    }
    /// 如果登录成功，则需要重设界面
    @objc fileprivate func logon(){
        yctitleItem.leftBarButtonItem = nil
        yctitleItem.rightBarButtonItem = nil
        NotificationCenter.default.removeObserver(self)
        /// view = nil， 在view展示时会调用 viewload，之后会调用 viewdidload 重设界面
        view = nil
    }
}


// MARK: - UITableViewDelegate,UITableViewDataSource
extension YCMainViewController: UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    //基类准备方法,子类负责实现
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    //判断是否是最后一行,做上啦刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        if row < 0 || section < 0 {
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        //如果是最后一行,且没有开始上拉刷新
        if row == count - 1 && !isPullup {
            //开始上拉刷新
            isPullup = true
            
            loadData()
        }
        
    }
}
